// 配置管理
class ConfigManager {
  constructor() {
    this.config = {
      defaultShowMenu: false,
    };
    this.init();
  }

  async init() {
    await this.loadConfig();
    this.bindEvents();
    this.updateUI();
  }

  async loadConfig() {
    try {
      const result = await chrome.storage.sync.get(["mdniceTocConfig"]);
      if (result.mdniceTocConfig) {
        this.config = { ...this.config, ...result.mdniceTocConfig };
      }
    } catch (error) {
      console.error("加载配置失败:", error);
    }
  }

  async saveConfig() {
    try {
      await chrome.storage.sync.set({
        mdniceTocConfig: this.config,
      });
      this.showSaveSuccess();
    } catch (error) {
      console.error("保存配置失败:", error);
      this.showSaveError();
    }
  }

  bindEvents() {
    const defaultShowMenuCheckbox = document.getElementById("defaultShowMenu");
    const saveBtn = document.getElementById("saveConfig");

    defaultShowMenuCheckbox.addEventListener("change", (e) => {
      this.config.defaultShowMenu = e.target.checked;
    });

    saveBtn.addEventListener("click", () => {
      this.saveConfig();
    });
  }

  updateUI() {
    const defaultShowMenuCheckbox = document.getElementById("defaultShowMenu");
    defaultShowMenuCheckbox.checked = this.config.defaultShowMenu;
  }

  showSaveSuccess() {
    const saveBtn = document.getElementById("saveConfig");
    const originalText = saveBtn.textContent;
    saveBtn.textContent = "✅ 保存成功";
    saveBtn.disabled = true;

    setTimeout(() => {
      saveBtn.textContent = originalText;
      saveBtn.disabled = false;
    }, 2000);
  }

  showSaveError() {
    const saveBtn = document.getElementById("saveConfig");
    const originalText = saveBtn.textContent;
    saveBtn.textContent = "❌ 保存失败";
    saveBtn.disabled = true;

    setTimeout(() => {
      saveBtn.textContent = originalText;
      saveBtn.disabled = false;
    }, 2000);
  }
}

// 初始化配置管理器
document.addEventListener("DOMContentLoaded", () => {
  new ConfigManager();
});
